from django.shortcuts import render, HttpResponse, redirect

from app00 import models
from app00.forms.account import *
from django.conf import settings
from utils.tencent.sms import send_sms_single
from django.http import JsonResponse

import random
from io import BytesIO
from utils.image_code import check_code

# 执行复杂查询 使用 & ｜ 时
from django.db.models import Q

import uuid
from datetime import datetime


def send_sms(request):
    """
        发送短息
    :param request:
    :return:
    """

    form = SendSmsForm(request, data=request.GET)
    if form.is_valid():
        return JsonResponse({'status': True})
    return JsonResponse({'status': False, 'error': form.errors})


def register(request):
    """
        用户信息注册
    :param request:
    :return:
    """
    if request.method == 'GET':
        form = RegisterModelForm(request)
        return render(request, 'register.html', {'form': form})
    form = RegisterModelForm(request, data=request.POST)
    if form.is_valid():
        # 实现保存功能
        instance = form.save()
        # 查询价格策略
        price_policy = models.PricePolicy.objects.filter(category=1, title='个人免费版').first()
        # 生成注册用户免费的价格策略
        models.Transaction.objects.create(
            status=2,
            order=str(uuid.uuid4()),
            user=instance,
            price_policy=price_policy,
            count=0,
            price=0,
            start_datetime=datetime.now()
        )
        return JsonResponse({'status': True, 'data': '/pubulisher_list/'})
    return JsonResponse({'status': False, 'error': form.errors})


def login_sms(request):
    """
     根据手机验证码进行登录
    :param request:
    :return:
    """
    if request.method == 'GET':
        form = loginSmsForm(request)
        return render(request, 'login_sms.html', {'form': form})
    form = loginSmsForm(request, data=request.POST)
    if form.is_valid():
        mobile_phone = form.cleaned_data['mobile_phone']
        # 根据手机号查询用户信息
        user_obj = models.UserInfo.objects.filter(mobile_phone=mobile_phone).first()
        request.session['user_id'] = user_obj.id
        request.session['username'] = user_obj.username
        request.session.set_expiry(60 * 60 * 24 * 14)
        return JsonResponse({'status': True, 'data': '/publisher_list/'})
    return JsonResponse({'status': False, 'error': form.errors})


def login(request):
    """
        用户名密码登录功能
    :param request:
    :return:
    """
    if request.method == 'GET':
        form = loginForm(request)
        return render(request, 'login.html', {'form': form})
    form = loginForm(request, data=request.POST)
    if form.is_valid():
        # 要去数据库进行校验
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']
        user_obj = models.UserInfo.objects \
            .filter(Q(email=username) | Q(mobile_phone=username)) \
            .filter(password=password) \
            .first()
        if user_obj:
            request.session['user_id'] = user_obj.id
            request.session['username'] = user_obj.username
            request.session.set_expiry(60 * 60 * 24 * 14)

            return redirect('/publisher_list/')

        form.add_error('username', '用户名或密码错误')
    return render(request, 'login.html', {'form': form})


def image_code(request):
    """
        生成图片验证码
    :param request:
    :return:
    """
    image_obj, code = check_code()
    # 将图片验证码保存到session中
    request.session['image_code'] = code
    request.session.set_expiry(60)

    stream = BytesIO()
    image_obj.save(stream, 'png')
    stream.getvalue()
    return HttpResponse(stream.getvalue())


def logout(request):
    """
        用户退出
    :param request:
    :return:
    """
    request.session.flush()
    return redirect('/publisher_list/')


# 出版社列表
def publisher_list(request):
    publisher = models.Publisher.objects.all()
    return render(request, 'publisher_list.html', {'publisher_list': publisher})


# 添加出版社
def add_publisher(request):
    if request.method == 'POST':
        new_publisher_name = request.POST.get('name')
        models.Publisher.objects.create(name=new_publisher_name)
        return redirect('/publisher_list/')
    return render(request, 'add_publisher.html')


# 删除出版社
def drop_publisher(request):
    drop_id = request.GET.get('id')
    drop_obj = models.Publisher.objects.get(id=drop_id)
    drop_obj.delete()
    return redirect('/publisher_list/')


# 编辑出版社
def edit_publisher(request):
    if request.method == 'POST':
        edit_id = request.GET.get('id')
        edit_obj = models.Publisher.objects.get(id=edit_id)
        new_name = request.POST.get('name')
        edit_obj.name = new_name
        edit_obj.save()
        return redirect('/publisher_list/')

    edit_id = request.GET.get('id')
    edit_obj = models.Publisher.objects.get(id=edit_id)
    return render(request, 'edit_publisher.html', {'publisher': edit_obj})


# 书籍的列表
def book_list(request):
    book = models.Book.objects.all()
    return render(request, 'book_list.html', {'book_list': book})


# 添加本书籍
def add_book(request):
    if request.method == 'POST':
        new_book_name = request.POST.get('name')
        publisher_id = request.POST.get('publisher_id')
        models.Book.objects.create(name=new_book_name, publisher_id=publisher_id)
        return redirect('/book_list/')

    res = models.Publisher.objects.all()
    return render(request, 'add_book.html', {'publisher_list': res})


# 删除本书籍
def drop_book(request):
    drop_id = request.GET.get('id')
    drop_obj = models.Book.objects.get(id=drop_id)
    drop_obj.delete()
    return redirect('/book_list/')


# 编辑本书籍
def edit_book(request):
    if request.method == 'POST':
        new_book_name = request.POST.get('name')
        new_publisher_id = request.POST.get('publisher_id')
        edit_id = request.GET.get('id')
        edit_obj = models.Book.objects.get(id=edit_id)
        edit_obj.name = new_book_name
        edit_obj.publisher_id = new_publisher_id
        edit_obj.save()
        return redirect('/book_list/')

    edit_id = request.GET.get('id')
    edit_obj = models.Book.objects.get(id=edit_id)
    all_publisher = models.Publisher.objects.all()
    return render(request, 'edit_book.html', {'book': edit_obj, 'publisher_list': all_publisher})


# 作者的列表
def author_list(request):
    author = models.Author.objects.all()
    return render(request, 'author_list.html', {'author_list': author})


# 添加个作者
def add_author(request):
    if request.method == 'POST':
        new_author_name = request.POST.get('name')
        models.Author.objects.create(name=new_author_name)
        return redirect('/author_list/')
    return render(request, 'add_author.html')


# 删除个作者
def drop_author(request):
    drop_id = request.GET.get('id')
    drop_obj = models.Author.objects.get(id=drop_id)
    drop_obj.delete()
    return redirect('/author_list/')


# 修改下作者
def edit_author(request):
    if request.method == 'POST':
        edit_id = request.GET.get('id')
        edit_obj = models.Author.objects.get(id=edit_id)
        new_author_name = request.POST.get('name')
        new_book_id = request.POST.getlist('book_id')
        edit_obj.name = new_author_name
        edit_obj.book.set(new_book_id)
        edit_obj.save()
        return redirect('/author_list/')

    edit_id = request.GET.get('id')
    edit_obj = models.Author.objects.get(id=edit_id)
    all_book = models.Book.objects.all()
    return render(request, 'edit_author.html', {
        'author': edit_obj,
        'book_list': all_book
    })



